<template>
  <scroll-view
    enable-back-to-top
    scroll-y
    class="customer"
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="getCustomerData"
  >
    <view
      style="
        background-color: #3775cb;
        padding: 15rpx 0;
        position: fixed;
        top: 0rpx;
        z-index: 999;
        width: 100%;
        box-shadow: 0 4rpx 6rpx rgba(240, 240, 240, 0.6);
      "
    >
      <u-search
        placeholder="关键词搜索"
        v-model="queryParams.name"
        @search="handleQuery"
        @custom="handleQuery"
        @change="handleQuery"
        margin="0 20rpx"
        :actionStyle="{
          color: '#ffffff',
        }"
      ></u-search>
    </view>
    <view class="list">
      <uni-list>
        <uni-list :border="true">
          <uni-list-chat
            v-for="(item, index) in customerList"
            :key="index"
            :title="item?.name"
            :avatar="item?.avatarUrl ? item?.avatarUrl : '/static/icons/avatar.png'"
            :note="'跟进成员：' + item?.followUserLabel"
            :to="`/pagesCustomer/customer/customerDetails?customerId=${item?.customerId}`"
            badge-positon="left"
          >
            <view class="chat-custom-right">
              <view style="margin-top: 14rpx">
                <image
                  style="width: 50rpx"
                  class="slot-image"
                  :src="item?.type === '1' ? '/static/icons/WeChat.png' : '/static/icons/wecom.png'"
                  mode="widthFix"
                ></image>
              </view>
            </view>
          </uni-list-chat>
        </uni-list>
      </uni-list>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ isFinish ? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>
</template>
<script setup lang="ts">
// 获取屏幕边界到安全区域距离
import { onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getCustomerListAPI } from '@/services/customer'
import { getContextApi, getCurExternalContactApi, registerApi } from '@/utils/wecom'

const { safeAreaInsets } = uni.getSystemInfoSync()

// 定义 porps
const props = defineProps<{}>()

// 请求参数
const queryParams = ref<any>({
  qwExternalUserid: '',
  entryType: '1',
  pageNum: 1,
  pageSize: 10,
})
const total = ref<any>(0)
// 获取订单列表
const customerList = ref<any[]>([])
// 是否加载中标记，用于防止滚动触底触发多次请求
const isLoading = ref(false)
// 是否分页结束
const isFinish = ref(false)
// 是否触发下拉刷新
const isTriggered = ref(false)
/** 重置 */
const reset = () => {
  queryParams.value.pageNum = 1
  queryParams.value.qwExternalUserid = ''
  customerList.value = []
  isFinish.value = false
}
/** 搜索按钮操作 */
const handleQuery = () => {
  reset()
  getCustomerData()
}

const getCustomerData = async () => {
  // 如果数据出于加载中，退出函数
  if (isLoading.value) return
  // 退出分页判断
  if (isFinish.value === true) {
    return
  }
  // 发送请求前，标记为加载中
  isLoading.value = true
  // 发送请求
  const res = await getCustomerListAPI(queryParams.value)
  // 发送请求后，重置标记
  isLoading.value = false
  total.value = res.total
  // 数组追加
  customerList.value.push(...res.rows)
  if (queryParams.value.qwExternalUserid && customerList.value.length > 0) {
    //模拟搜索效果
    queryParams.value.name = customerList.value[0].name
    console.log('queryParams.value.name', queryParams.value.name)
  }
  // 分页条件
  if (customerList.value.length < res.total) {
    // 页码累加
    queryParams.value.pageNum++
  } else {
    // 分页已结束
    isFinish.value = true
  }
}

// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 重置数据
  queryParams.value.page = 1
  customerList.value = []
  isFinish.value = false
  // 加载数据
  await getCustomerData()
  // 关闭动画
  isTriggered.value = false
}

onShow(async () => {
  await registerApi(['getCurExternalContact', 'getContext'])
  await getCurExternalContact()
  getCustomerData()
})

const getCurExternalContact = async () => {
  let qwEntry = await getContextApi()
  if (qwEntry === 'single_chat_tools') {
    queryParams.value.qwExternalUserid = await getCurExternalContactApi()
  }
}
</script>

<style lang="scss">
.customer {
  .list {
    margin-top: 115rpx;
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
